﻿using CADIfox_MVVM.Extension;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CADIfox_MVVM.Command
{
    public class LineConnectCommand
    {
        [CommandMethod("ConnectLine")]
        public static void Create()
        {
            using var tr = new DBTrans();

            var enities = tr.Editor.SelectEntities(tr);

            var curves = enities.FindAll(x => x is Curve).Select(x => x as Curve).ToList();

            var points = new List<Point3d>();

            foreach (var curve in curves)
            {
                points.Add(curve.StartPoint);
                points.Add(curve.EndPoint);
            }

            var xSortPoints =  points.OrderBy(x => x.X).ToList();

            var splitPoints = xSortPoints.Skip(1).Take(xSortPoints.Count-2).ToList();

            List<List<Point3d>> result = new List<List<Point3d>>();
            int count = 0;
            for (int i = 0; i < splitPoints.Count-1; i += 2)
            {
                result.Add(new List<Point3d> { splitPoints[i], splitPoints[i + 1] });
            }


            foreach (var resP in result)
            {
                
                if (!resP[0].Equals(resP[1]))
                {
                    var ff = new Line(resP[0], resP[1]);
                    tr.CurrentSpace.AddEntity(ff);
                }
            }

            //var impliedSelect = tr.Editor.SelectImplied();
            //if (impliedSelect.Status == PromptStatus.OK)
            //{
            //    var seletedObjects = impliedSelect.Value.GetObjectIds();


            //    foreach (var seletedObject in seletedObjects)
            //    {
            //        var entity = tr.GetObject<Entity>(seletedObject);
            //    }
            //}
        }
    }
}
